package com.qihetimes.earthangel.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.qihetimes.earthangel.common.ApiException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 短信服务
 *
 * @author ：f4cklangzi@gmail.com
 * @date ：Created At 2021/12/10
 */
@Slf4j
@Service
public class SmsService {
    
    private static final long EXPIRE = 60 * 5;
    
    private static final String SMS_PREFIX = "SMS_CODE:";
    
    private static final String PHONE_RE = "^1\\d{10}$";
    
    @Resource
    private RedisService redisService;
    
    @Resource
    private Client client;
    
    @SneakyThrows
    public void send(String phone) {
        if (!isPhone(phone)) {
            throw new ApiException("手机号格式错误!");
        }
        String key = getKeyByPhone(phone);
        Object code = redisService.get(key);
        if (code != null) {
            redisService.expire(key, EXPIRE);
            return;
        }
        code = RandomUtil.randomNumbers(6);
        code = 8888;
        redisService.set(key, code, EXPIRE);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
            .setPhoneNumbers(phone)
            .setSignName("11")
            .setTemplateParam("{\"name\":\"" + code + "\"}")
            .setTemplateCode("SMS_229646434");
        try {
            // SendSmsResponse response = client.sendSms(sendSmsRequest);
            // if (!"OK".equals(response.body.code)) {
            //     throw new CustomerException(response.body.message);
            // }
        } catch (Exception exception) {
            redisService.remove(key);
            log.error("短信{}发送失败", phone, exception);
            throw new ApiException("发送失败:" + exception.getMessage());
        }
    }
    
    public boolean checkCode(String phone, Integer code) {
        if (!isPhone(phone)) {
            return false;
        }
        String key = getKeyByPhone(phone);
        Integer redisCode = (Integer) redisService.get(key);
        boolean res = code.equals(redisCode);
        if (res) {
            redisService.remove(key);
            return true;
        }
        return false;
    }
    
    private String getKeyByPhone(String phone) {
        return SMS_PREFIX + phone;
    }
    
    private boolean isPhone(String phone) {
        return ReUtil.isMatch(PHONE_RE, phone);
    }
}
